package db;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class Mapper
{
	private Map<String, String> data;
	private FileHandler fh;
	
	public Mapper(String filename)
	{
		fh = new FileHandler(filename);
		try
		{
			data = fh.getDataFromFile();
		}
		catch(IOException ex)
		{
			data = new ConcurrentHashMap<String, String>();
		}
	}
	
	public String getAddress(String name)
	{
		return this.data.get(name);
	}
	
	public Set<String> getNames()
	{
		return this.data.keySet();
	}
	
	public boolean containsAddress(String address)
	{
		return this.data.containsValue(address);
	}
	
	public boolean containsName(String name)
	{
		return this.data.containsKey(name);
	}
	
	public void addPeer(String name, String address)
	{
		this.data.put(name, address);
	}
	
	public void addPeers(Map<String, String> peers)
	{
		this.data.putAll(peers);		
	}
	
	public void removePeer(String name)
	{
		this.data.remove(name);
	}
	
	public String getPeersAsJSON()
	{
		String json = "[\n";
		
		Set<String> names = data.keySet();
		Iterator<String> iter = names.iterator();
		
		while(iter.hasNext())
		{
			String name = iter.next();
			String address = data.get(name);
			
			json += "[\"" + name + "\",\"" + address + "\"]";
			if(iter.hasNext()) json += ",";
			json += "\n";
		}
		
		json += "]";
		
		return json;
	}
	
	public String[] getPeersArray()
	{
		List<String> list = new ArrayList<String>();
		
		Iterator<String> iter = this.getNames().iterator();
		
		while(iter.hasNext())
		{
			String name = iter.next();
			String address = this.getAddress(name);
			
			list.add(name + "@" + address);
		}
		
		String[] array = new String[list.size()];
		list.toArray(array);
		
		return array;
	}
	
	public boolean update()
	{
		boolean result;
		try
		{
			fh.putDataToFile(data);
			result = true;
		}
		catch (IOException e)
		{
			result = false;
		}
		
		return result;
	}
}
